<?php
namespace app\api\model\sharewifi;

use app\common\model\sharewifi\User as UserModel;
use hema\wechat\Wxapp;
use hema\wechat\WxBizDataCrypt;

/**
 * 用户模型类
 */
class User extends UserModel
{
    /**
     * 隐藏字段
     */
    protected $hidden = [];

    /**
     * 微信小程序登录
     */
    public function wxappLogin(array $data)
    {
        $userInfo = json_decode(htmlspecialchars_decode($data['user_info']), true);
        $config = get_addons_config('sharewifi');
        // 微信登录
        $wx = new Wxapp($config);
        if(!$result = $wx->code2Session($data['code'])){
            $this->error = $wx->getError();
            return false;
        }
        //用户不存在才执行
        if (!$user = $this->where(['open_id' => $result['openid']])->find()) {
            isset($result['unionid']) && $userInfo['union_id'] = $result['unionid'];
            $userInfo['nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $userInfo['nickName']);
            $userInfo['avatar'] = $userInfo['avatarUrl'];
            $userInfo['open_id'] = $result['openid'];
            $userInfo['recommender'] = $data['recommender'];//推荐人
            $this->save($userInfo);
        }else{
            $userInfo =[
                'login_count' => $user['login_count'] + 1,//登录次数加1
                'nickname' => preg_replace('/[\xf0-\xf7].{3}/', '', $userInfo['nickName']),//更新昵称
                'avatar' => $userInfo['avatarUrl'],
            ];
            isset($result['unionid']) && $userInfo['union_id'] = $result['unionid'];
            $user->save($userInfo);
        }
        $user = $this->where(['open_id' => $result['openid']])->find();
        return $user;
    }
    
    /**
     * 获取用户手机号
     */
    public function getPhoneNumber($post)
    {
        $config = get_addons_config('sharewifi');
        // 微信登录
        $wx = new Wxapp($config);
        if(!$result = $wx->code2Session($post['code'])){
            $this->error = $wx->getError();
            return false;
        }
        $sessionKey = $result['session_key'];
        $encryptedData= $post['encryptedData'];
        $iv = $post['iv'];
        $pc = new WxBizDataCrypt($sessionKey,0,$config['app_id']);
        $errCode = $pc->decryptData($encryptedData,$iv,$data);
        $data = json_decode($data,true);
        if (isset($data['phoneNumber'])) {
            $this->phone = $data['phoneNumber'];
            $this->save();
            return $data['phoneNumber'];
        }
        return false;

    }

}